/* eslint-disable react/jsx-key */
import React, { useState } from 'react';
import s from './style.module.less';
import CopyText from '@/components/copy';
import { Link } from 'react-router-dom';
import {
  Dialog,
  Pagination,
  Button,
  Tooltip,
  Textarea,
  Input,
  Confirm,
  Loading,
  Form,
  Message,
  Icon,
  AntdTable,
} from '@knownsec/react-component';
import { filterNull } from '@/utils';
import { Table, ConfigProvider } from 'antd';
import i from '@/common.module.css';
import { BUG_GRADE } from '@/common/common';
import { changeList, changeDEL, changePUT } from '~/API';
import { uniqBy } from 'lodash-es';
import cn from 'classnames';
import { datetime } from '@/common/formatter';

const keyforms = {
  name: '模版名称',
  plugin_list: '模版插件',
  description: '模版描述',
};
const defaultSearch = {
  key: '',
  target_group_name: '',
  target_name: '',
  page: 1,
  count: 10,
};
const CusLoading = <Loading label="" />;
const initForm = { name: '', description: '', plugin_list: [] };
export default function keyword() {
  const [selectIds, setSelTable] = useState([]);
  const [loading, setLoading] = useState(true);
  const [visibleD, setVisibleD] = useState(''); //查看详情
  const [total, setTotal] = useState(0);
  const [searchInfo, setSearchInfo] = useState(defaultSearch);

  const [page, setPage] = useState({ page: 1, limit: 10 });
  const [tableData, setTableData] = useState([]);
  const columns = [
    {
      title: '业务系统',
      dataIndex: 'target_url',
      render: (e, row) => {
        const name = row.target_name ? row.target_name : row.target_title;
        return (
          <Tooltip
            overlay={
              <>
                <p>
                  业务系统：
                  <CopyText text={e} />
                </p>
                <p>业务系统名称：{name || '暂未设置'}</p>
              </>
            }
            placement="topLeft"
          >
            <div>
              <Link
                className={s.hrefName}
                to="#"
                onClick={() => {
                  window.open(e);
                }}
              >
                {e}
              </Link>
              <div className={s.targetName} style={{ color: name ? '#2A2B31' : '#ccc' }}>
                {name || '- -'}
              </div>
            </div>
          </Tooltip>
        );
      },
    },
    {
      title: '任务组名称',
      dataIndex: 'target_group_name',
      render: (e) => {
        return e || '- -';
      },
    },
    {
      title: '基准页面数',
      dataIndex: 'base_page_count',
      render: (e) => {
        return <span>{isNaN(e) ? '- -' : e}</span>;
      },
    },
    {
      title: '上次更新时间',
      dataIndex: 'updated_at',
      render: (e) => {
        return <span>{datetime(e) || '--'}</span>;
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      className: s.option,
      render: (e, row) => {
        return (
          <>
            <span
              className={s.operation}
              onClick={() => {
                editModule(row);
              }}
            >
              更新
            </span>
            <span
              className={s.operation}
              onClick={() => {
                delModule([row.id]);
              }}
            >
              删除
            </span>
          </>
        );
      },
    },
  ];
  const getList = async (e) => {
    const e_ = e ? e : page;
    setTableData([]);
    setLoading(true);
    const list = await changeList(e_);
    if (!list.data.base_page[0] && page.page > 1) {
      setPage({ limit: page.limit, page: page.page - 1 });
      onSearch({ limit: page.limit, page: page.page - 1 });
      return false;
    }
    list.data.base_page.map((item) => {
      item.id = item.base_task_id;
      item.key = item.base_task_id;
    });
    setTotal(list.data.count);

    setTableData(list.data.base_page);
    setLoading(false);
  };
  function onSearchChange(data) {
    setPage(data);
    getList(data);
  }

  function delModule(e) {
    Confirm({
      title: '提示',
      pro: true,
      message: <div className="confirmbox">您确认要删除选中的变更基准信息吗？</div>,
      onconfirm: () => {
        const ids = e ? e : selectIds;
        const params = { base_task_id: ids };
        changeDEL(params).then((res) => {
          if (res.status == 'success') {
            setSelTable([]);
            //任务是异步的，立即刷新可能引擎那边还没删掉
            setTimeout(() => {
              onSearch(page);
            }, 2000);
            Message.show({
              pro: true,
              type: 'success',
              message: '删除成功',
              showClose: false,
            });
          }
        });
      },
      oncancel: () => {},
    });
  }
  const editModule = async (row) => {
    Confirm({
      title: '提示',
      pro: true,
      message: (
        <div className="confirmbox">
          系统将以最新爬取页面信息作为基准，您确认要更新该资产变更基准信息？
        </div>
      ),
      onconfirm: async () => {
        const res = await changePUT({ base_task_id: [row.base_task_id] });
        if (res.status === 'success') {
          Message.show({
            pro: true,
            type: 'success',
            message: '更新成功',
            showClose: false,
          });
        }
      },
      oncancel: () => {},
    });
  };
  const onSearch = ({ page, limit, data }) => {
    // let params = {...e, page: 1, count: 10 };
    const params = filterNull(
      Object.assign(data || searchInfo, { page: page || 1, limit: limit || 10 })
    );
    getList(params);
  };
  const rowSelection = {
    selectedRowKeys: selectIds,
    onChange: (selectedRowKeys) => {
      setSelTable(selectedRowKeys);
    },
    getCheckboxProps: (record) => ({
      disabled: record.id === '',
    }),
  };
  const CustomSIze = () => {
    return <div className={cn(i.p30, i.w100p, i.blackLineColor, i.fs14, i.tac)}>暂无数据</div>;
  };
  React.useEffect(() => {
    getList();
  }, []);
  return (
    <div className={s.wordMain}>
      {/* <Loading show={loading} label="" /> */}
      <div className={s.tool2}>
        <Input
          pro
          value={searchInfo.target_group_name}
          search
          clear
          autoComplete={'off'}
          onSearch={onSearch}
          className={cn('search-button', s.mr0)}
          placeholder="搜索任务组名称"
          maxlength={32}
          onChange={(e) => {
            setSearchInfo({ ...searchInfo, target_group_name: e.value });
            if (!e.e) {
              const data={...searchInfo,target_group_name:''}
              onSearch({data})
              return;
            }
          }}
        />
        <Input
          pro
          value={searchInfo.target_name}
          search
          clear
          autoComplete={'off'}
          onSearch={onSearch}
          className={cn('search-button', s.mr0)}
          placeholder="搜索业务系统名称"
          maxlength={32}
          onChange={(e) => {
            setSearchInfo({ ...searchInfo, target_name: e.value });
            if (!e.e) {
              const data={...searchInfo,target_name:''}
              onSearch({data})
              return;
            }
          }}
        />
        <Input
          pro
          value={searchInfo.target_url}
          search
          clear
          autoComplete={'off'}
          onSearch={onSearch}
          className={cn('search-button', s.mr0)}
          placeholder="搜索业务系统地址"
          maxlength={32}
          onChange={(e) => {
            setSearchInfo({ ...searchInfo, target_url: e.value });
            if (!e.e) {
              const data={...searchInfo,target_url:''}
              onSearch({data})
              return;
            }
          }}
        />
      </div>
      <div>
        <Button
          disabled={!selectIds.length}
          onClick={() => {
            delModule();
          }}
          className={cn(s.mr20, 'delete-btn', 'p0')}
          pro
          type="text"
        >
          删除
        </Button>
      </div>
      <ConfigProvider renderEmpty={CustomSIze}>
        <AntdTable
          rowSelection={{
            ...rowSelection,
          }}
          loading={loading ? { indicator: CusLoading } : false}
          columns={columns}
          dataSource={tableData}
          className={s.table}
          pagination={false}
        />
      </ConfigProvider>
      {total > 10 && (
        <Pagination
          key={Number(123)}
          className={s.pagination}
          current={page.page}
          showQuickJumper={{ goButton: true }}
          showSizeChanger={true}
          pageSize={page.limit}
          pageSizeOptions={['10', '20', '50']}
          total={total}
          showTotal={(total) => `共${total}条`}
          onChange={(page, size) => {
            setPage({ limit: size, page: page });
            onSearch({ page, limit: size });
          }}
        />
      )}
      {/* 查看 */}
      <Dialog
        className={cn(s.moduleDialog2, s.w840)}
        title="查看详情"
        maskClosable={true}
        cancelText=""
        confirmText="关闭"
        onsubmit={() => setVisibleD('')}
        onhide={() => {
          setVisibleD('');
        }}
        visible={visibleD}
      >
        <div className={cn(s.p24)}>
          <table className={s.diaTab}>
            <tr>
              <td className={s.keyTd}>模版名称</td>
              <td>
                {visibleD.display_name?.zh_cn ? visibleD.display_name.zh_cn : visibleD.description}
              </td>
            </tr>
            <tr>
              <td className={s.keyTd}>含插件数</td>
              <td>{visibleD?.plugins_count}</td>
            </tr>{' '}
            <tr>
              <td className={s.keyTd}>插件详情</td>
              <td className={s.keyDet}>
                <div className={s.detailTD}>
                  {visibleD &&
                    Object.entries(visibleD?.plugin_types).map(([key, val]) => {
                      return (
                        <>
                          <p className={s.detailP}>
                            <span>{key} </span>
                          </p>
                          <div className={s.detailD}>
                            {val.map((e, i) => {
                              return (
                                <span className={s.detailSpan} title={s.detail}>
                                  {e}
                                </span>
                              );
                            })}
                            {val.length % 2 !== 0 && (
                              <span className={s.detailSpan} title={s.detail}></span>
                            )}
                          </div>
                          <p style={{ height: '2rem' }}></p>
                        </>
                      );
                    })}
                </div>
              </td>
            </tr>
          </table>
        </div>
      </Dialog>
    </div>
  );
}
